package org.jeecg.modules.hc.utils;

import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import static com.wechat.pay.contrib.apache.httpclient.constant.WechatPayHttpHeaders.WECHAT_PAY_SERIAL;
import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.HttpHeaders.CONTENT_TYPE;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;


/**
 * 微信支付专用类 请求操作方法
 *
 * @author Administrator
 */
@Slf4j
public class HttpUtil {

    /**
     * 发起批量转账API 批量转账到零钱
     *
     * @param requestUrl
     * @param requestJson       组合参数
     * @param wechatPayserialNo 商户证书序列号
     * @param privatekeypath    商户私钥证书路径
     * @return
     */
    public static String postTransBatRequest(
            String requestUrl,
            String requestJson,
            String wechatPayserialNo,
            String mchId,
            String privatekeypath, String url) {
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        CloseableHttpClient httpClient = null;
        try {
            HttpPost httpPost = createHttpPost(requestUrl, requestJson, wechatPayserialNo, mchId, privatekeypath, url);
            httpClient = HttpClients.createDefault();
            //发起转账请求
            response = httpClient.execute(httpPost);
            log.info("response:{}", response);
            entity = response.getEntity();//获取返回的数据
            log.info("-----getHeaders.Request-ID:" + response.getHeaders("Request-ID"));
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (httpClient != null) {
                    httpClient.close();
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 账单查询
     *
     * @param requestUrl        请求完整地址
     * @param wechatPayserialNo 商户证书序列号
     * @param privatekeypath    商户私钥证书路径
     * @param privatekeypath    支付秘钥
     * @return
     */
    public static String getTransBatRequest(
            String requestUrl,
            String wechatPayserialNo,
            String mchId,
            String privatekeypath, String url) throws NotFoundException {
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        CloseableHttpClient httpClient = null;
        try {
            HttpGet httpPost = createHttpGet(requestUrl, wechatPayserialNo, mchId, privatekeypath, url);
            httpClient = HttpClients.createDefault();
            //发起转账请求
            response = httpClient.execute(httpPost);
            log.info("response:{}", response);
            entity = response.getEntity();//获取返回的数据
            log.info("-----getHeaders.Request-ID:" + response.getHeaders("Request-ID"));
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param requestUrl        请求完整地址
     * @param requestJson       请求参数
     * @param wechatPayserialNo 支付证书序列号
     * @param mchId             商户号
     * @param privatekeypath    私钥路径
     * @param ServletPath       相对路径
     * @return
     */
    private static HttpPost createHttpPost(String requestUrl,
                                           String requestJson,
                                           String wechatPayserialNo,
                                           String mchId,
                                           String privatekeypath, String ServletPath) {
        //商户私钥证书
        HttpPost httpPost = new HttpPost(requestUrl);
        // NOTE: 建议指定charset=utf-8。低于4.4.6版本的HttpCore，不能正确的设置字符集，可能导致签名错误
        httpPost.addHeader(ACCEPT, APPLICATION_JSON.toString());
        httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON.toString());
        //"55E551E614BAA5A3EA38AE03849A76D8C7DA735A");
        httpPost.addHeader(WECHAT_PAY_SERIAL, wechatPayserialNo);

        //-------------------------核心认证 start-----------------------------------------------------------------
        String strToken = null;
        try {
            log.info("requestJson:{}", requestJson);
            strToken = VechatPayV3Util.getToken("POST",
                    ServletPath,
                    requestJson, mchId, wechatPayserialNo, privatekeypath);
        } catch (Exception e) {
            log.error("createHttpPost error:", e);
            e.printStackTrace();
        }
        StringEntity reqEntity = new StringEntity(requestJson, APPLICATION_JSON);
        log.info("token " + strToken);
        // 添加认证信息
        httpPost.addHeader("Authorization",
                "WECHATPAY2-SHA256-RSA2048" + " "
                        + strToken);
        //---------------------------核心认证 end---------------------------------------------------------------
        httpPost.setEntity(reqEntity);
        return httpPost;
    }

    /**
     * 创建get 请求
     *
     * @param requestUrl        请求完整地址
     * @param wechatPayserialNo 支付证书序列号
     * @param mchId             商户号
     * @param privatekeypath    私钥路径
     * @param ServletPath       相对路径  请求地址上如果有参数 则此处需要带上参数
     * @return HttpGet
     */
    private static HttpGet createHttpGet(String requestUrl,
                                         String wechatPayserialNo,
                                         String mchId,
                                         String privatekeypath, String ServletPath) {
        //商户私钥证书
        HttpGet httpGet = new HttpGet(requestUrl);
        // NOTE: 建议指定charset=utf-8。低于4.4.6版本的HttpCore，不能正确的设置字符集，可能导致签名错误
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Accept", "application/json");
        //"55E551E614BAA5A3EA38AE03849A76D8C7DA735A");
        httpGet.addHeader("Wechatpay-Serial", wechatPayserialNo);
        //-------------------------核心认证 start-----------------------------------------------------------------
        String strToken = null;
        try {
            strToken = VechatPayV3Util.getToken("GET",
                    ServletPath,
                    "", mchId, wechatPayserialNo, privatekeypath);
        } catch (Exception e) {
            log.error("createHttpGet error:", e);
            e.printStackTrace();
        }

        log.info("token " + strToken);
        // 添加认证信息
        httpGet.addHeader("Authorization",
                "WECHATPAY2-SHA256-RSA2048" + " "
                        + strToken);
        //---------------------------核心认证 end---------------------------------------------------------------
        return httpGet;
    }
}
